﻿$(function () {
    $("[id$=TextField]").each(function () {
        var availableTags = Array();
        $(this).next("select").children("option").each(function () {
            availableTags.push({ label: $(this).text(), value: $(this).val() });
        });

        if (availableTags.length > 0) {
            var input = $(this);

            var select = input.next("select");

            select.hide();

            input.after("<span><img class='ms-taxonomy-browser-button' src='/_layouts/images/EMMCopyTerm.png' style='vertical-align:bottom' tabindex='0'></span>");
            
            if (select.children("option[selected=selected]").length == 0) {
                select.val(availableTags[0].value);
            }

            input.val(select.children("option[selected=selected]").text());

            input.autocomplete({
                source: availableTags,
                focus: function (event, ui) {
                    input.val(ui.item.label);
                    select.val(ui.item.value);
                    return false;
                },
                select: function (event, ui) {
                    input.val(ui.item.label);
                    select.val(ui.item.value);
                    return false;
                },
                minLength: 0
            });

            input.click(function () {
                input.autocomplete("search", input.val());
            });

            input.focusout(function () {
                var i = 0;
                for (i = 0; i < availableTags.length; i++) {
                    if (availableTags[i].label == input.val()) {
                        break;
                    }
                }
                if (i < availableTags.length) {
                    input.val(availableTags[i].label);
                    select.val(availableTags[i].value);
                } else {
                    input.val(select.children("option[selected=selected]").text());
                }

                return false;
            });
        }
    });
});